/**
 * <p>Title: liteflow</p>
 * <p>Description: 轻量级的组件式流程框架</p>
 * @author Bryan.Zhang
 * @email weenyc31@163.com
 * @Date 2020/4/1
 */
package io.mft.flow.core.executable.condition;

import java.util.List;

import io.mft.commons.function.ExecuteReturn;
import io.mft.commons.function.response.ResponseReader;
import io.mft.commons.function.response.ResponseWriter;
import io.mft.flow.core.executable.Condition;
import io.mft.flow.core.executable.ConditionExecutable;
import io.mft.flow.core.executable.ConditionType;
import io.mft.flow.core.executable.Executable;
import io.mft.flow.core.executable.drive.ChainConditionDriver;
import io.mft.flow.core.executable.drive.ConditionDriveSourceProvider;
import io.mft.flow.core.executable.drive.ConditionDriverType;
import io.mft.flow.data.ChainContext;
import io.mft.flow.data.ExecutableResponse;

public class SyncCondition extends Condition implements ConditionDriveSourceProvider{

	public SyncCondition(ChainConditionDriver chainConditionDriver, List<ConditionExecutable> nodeList) {
		super(chainConditionDriver, nodeList);

	}

	@Override
	public ConditionType conditionType() {
		return ConditionType.sync;
	}

	@Override
	public ExecuteReturn execute(ChainContext context) throws Exception {
		ExecuteReturn executeReturn = ExecuteReturn.builder().build();
		for (ConditionExecutable conditionExecutable : getNodeList()) {
			Executable executable=getFlowExecutor().getExecutable(conditionExecutable.getExecutableType(),conditionExecutable.getExecutableId());
			String uniqueId = conditionExecutable.getUniqueId();
			ChainContext chainContext=context;
			if (chainConditionDriver().conditionDriverType() == ConditionDriverType.pipeline) {
				ResponseWriter responseWriter = (ResponseWriter) chainConditionDriver();
				ResponseReader responseReader = (ResponseReader) chainConditionDriver();
				ExecutableResponse response = new ExecutableResponse(responseWriter, responseReader);
				chainContext = new ChainContext(chainCondition.getChain().getChainId(), context.getChainInitialRequest(),context.getRequest(), response,uniqueId);
			}else {
				chainContext=new ChainContext(chainCondition.getChain().getChainId(), context.getChainInitialRequest(),context.getRequest(), context.getResponse(),uniqueId);
			}
			executeReturn = executable.execute(chainContext);
			if (executeReturn.getCode() != 0) {
				chainContext.getResponse().clear();
				break;
			}
		}
		if (executeReturn.getCode()==0) {//当前逻辑单元正常返回则执行下一个逻辑单元节点
			if (chainCondition.getNextChainCondition() != null&&chainConditionDriver().conditionDriverType() != ConditionDriverType.pipeline) {
				executeReturn = chainConditionDriver.drive(context,this);
			}
		}
		return executeReturn;
	}

	@Override
	public ProvideResult provide(ChainContext context) {
		ProvideResult provideResult=new ProvideResult();
		provideResult.setList(context.getResponse().listObject());
		return provideResult;
	}
}
